<?php

namespace backend\modules\sys\controllers;

use Yii;
use backend\models\User;
use yii\web\NotFoundHttpException;
use backend\models\ActionLog;
use c006\alerts\Alerts;

class PasswordController extends \yii\web\Controller
{
    public function actionIndex()
    {

        $id = Yii::$app->user->id;
        $model = $this->findModel($id);
        $model->setScenario('admin-password');
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->authManager->revokeAll($id);
            Yii::$app->authManager->assign(Yii::$app->authManager->getRole($model->role), $id);
            Alerts::setMessage("密码更新成功");
            Alerts::setAlertType(Alerts::ALERT_SUCCESS);
            ActionLog::log(Yii::t('app', 'Change Password'));
            return $this->redirect(['index']);
        } else {
            //print_r($model->errors);exit;
            return $this->render('index', [
                'model' => $model,
            ]);
        }
    }

    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
